import React, { useState, useEffect } from 'react'
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Switch,
  TreeSelect,
  message,
  Row,
  Col,
  Divider,
  Tag,
  Dropdown,
  Avatar
} from 'antd'
import type { MenuProps } from 'antd'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  MenuOutlined,
  FolderOutlined,
  FileOutlined,
  ReloadOutlined,
  LinkOutlined,
  ExpandOutlined,
  CompressOutlined,
  MoreOutlined,
  SettingOutlined,
  CopyOutlined,
  SortAscendingOutlined
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import { MenuItem } from '@/types/menu'
import menuService from '@/services/menu'
import styles from './Menus.module.css'

interface MenuTableData extends MenuItem {
  children?: MenuTableData[]
}

const Menus: React.FC = () => {
  // 状态管理
  const [loading, setLoading] = useState(false)
  const [menuData, setMenuData] = useState<MenuTableData[]>([])
  const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([])
  const [allKeys, setAllKeys] = useState<React.Key[]>([])
  const [modalVisible, setModalVisible] = useState(false)
  const [modalType, setModalType] = useState<'create' | 'edit'>('create')
  const [currentMenu, setCurrentMenu] = useState<MenuItem | null>(null)
  const [parentOptions, setParentOptions] = useState<MenuTableData[]>([])
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  
  const [form] = Form.useForm()

  // 获取菜单数据
  const fetchMenus = async () => {
    try {
      setLoading(true)
      const response = await menuService.getMenuList()
      if (response.code === 200) {
        const tableData = transformToTableData(response.data)
        setMenuData(tableData)
        setParentOptions(tableData)
        // 获取所有节点的keys
        const keys = getAllKeys(tableData)
        setAllKeys(keys)
        // 默认展开所有节点
        setExpandedRowKeys(keys)
      } else {
        message.error(response.message || '获取菜单数据失败')
      }
    } catch (error) {
      console.error('获取菜单数据失败:', error)
      message.error('获取菜单数据失败')
    } finally {
      setLoading(false)
    }
  }

  // 转换菜单数据为表格数据
  const transformToTableData = (menus: MenuItem[]): MenuTableData[] => {
    return menus.map(menu => ({
      ...menu,
      children: menu.children ? transformToTableData(menu.children) : undefined
    }))
  }

  // 获取所有节点的key
  const getAllKeys = (nodes: MenuTableData[]): React.Key[] => {
    const keys: React.Key[] = []
    const traverse = (nodeList: MenuTableData[]) => {
      nodeList.forEach(node => {
        keys.push(node.key)
        if (node.children) {
          traverse(node.children)
        }
      })
    }
    traverse(nodes)
    return keys
  }

  // 展开所有节点
  const expandAll = () => {
    setExpandedRowKeys(allKeys)
  }

  // 折叠所有节点
  const collapseAll = () => {
    setExpandedRowKeys([])
  }

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的菜单')
      return
    }
    
    Modal.confirm({
      title: '批量删除菜单',
      content: `确定删除选中的 ${selectedRowKeys.length} 个菜单吗？`,
      onOk: async () => {
        try {
          // 这里需要根据后端API调整
          for (const key of selectedRowKeys) {
            const menu = findMenuByKey(menuData, key as string)
            if (menu?.id) {
              await menuService.deleteMenu(menu.id)
            }
          }
          message.success('批量删除成功')
          setSelectedRowKeys([])
          fetchMenus()
        } catch (error) {
          console.error('批量删除失败:', error)
          message.error('批量删除失败')
        }
      }
    })
  }

  // 查找菜单项
  const findMenuByKey = (nodes: MenuTableData[], key: string): MenuTableData | null => {
    for (const node of nodes) {
      if (node.key === key) return node
      if (node.children) {
        const found = findMenuByKey(node.children, key)
        if (found) return found
      }
    }
    return null
  }

  // 定义表格列
  const columns: ColumnsType<MenuTableData> = [
    {
      title: (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <MenuOutlined />
          <span>显示名称</span>
        </div>
      ),
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: true,
      render: (text: string, record: MenuTableData) => {
        const hasChildren = record.children && Array.isArray(record.children) && record.children.length > 0
        const isHidden = Boolean(record.hidden)
        
        return (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <Avatar 
              size="small" 
              className={styles.menuAvatar}
              style={{ 
                backgroundColor: hasChildren ? '#1890ff' : '#52c41a',
                color: '#fff'
              }}
              icon={hasChildren ? <FolderOutlined /> : <FileOutlined />}
            />
            <span style={{ 
              opacity: isHidden ? 0.5 : 1,
              textDecoration: isHidden ? 'line-through' : 'none',
              fontWeight: hasChildren ? 500 : 400
            }}>
              {text || '未命名菜单'}
            </span>
            {isHidden && (
              <Tag color="default" className={styles.statusTag}>隐藏</Tag>
            )}
          </div>
        )
      }
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 80,
      align: 'center',
      render: (_, record: MenuTableData) => {
        const hasChildren = record.children && Array.isArray(record.children) && record.children.length > 0
        return (
          <Tag 
            color={hasChildren ? 'blue' : 'green'}
            className={styles.statusTag}
          >
            {hasChildren ? '目录' : '菜单'}
          </Tag>
        )
      }
    },
    {
      title: '路由地址',
      dataIndex: 'path',
      key: 'path',
      width: 180,
      ellipsis: true,
      render: (text: string) => text && typeof text === 'string' ? (
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <LinkOutlined style={{ color: '#1890ff' }} />
          <span style={{  fontSize: '12px' }}>{text}</span>
        </div>
      ) : (
        <span style={{ color: '#ccc' }}>-</span>
      )
    },
    {
      title: '组件',
      dataIndex: 'component',
      key: 'component',
      width: 120,
      ellipsis: true,
      render: (text: string) => text && typeof text === 'string' ? (
        <span style={{ 
      
          fontSize: '11px',
          backgroundColor: '#f5f5f5',
          padding: '2px 6px',
          borderRadius: '4px',
          color: '#666'
        }}>
          {text}
        </span>
      ) : (
        <span style={{ color: '#ccc' }}>-</span>
      )
    },
    {
      title: (
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <EyeOutlined />
          <span>是否可见</span>
        </div>
      ),
      key: 'visible',
      width: 100,
      align: 'center',
      render: (_, record: MenuTableData) => (
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          {record.hidden ? (
            <Tag color="default" className={styles.statusTag}>隐藏</Tag>
          ) : (
            <Tag color="success" className={styles.statusTag}>显示</Tag>
          )}
        </div>
      )
    },
    {
      title: (
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer' }}>
          <SortAscendingOutlined />
          <span>排序</span>
        </div>
      ),
      dataIndex: 'sort',
      key: 'sort',
      width: 80,
      align: 'center',
      render: (sort: number = 0) => (
        <Tag 
          color="blue" 
          className={styles.statusTag}
          style={{ }}
        >
          {sort}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record: MenuTableData) => {
        const moreMenuItems: MenuProps['items'] = [
          {
            key: 'copy',
            icon: <CopyOutlined />,
            label: '复制菜单',
          },
          {
            key: 'settings',
            icon: <SettingOutlined />,
            label: '菜单设置',
          },
          {
            type: 'divider',
          },
          {
            key: 'delete',
            icon: <DeleteOutlined />,
            label: '删除菜单',
            danger: true,
          },
        ]

        const handleMoreMenuClick = ({ key }: { key: string }) => {
          switch (key) {
            case 'copy':
              // 复制菜单逻辑
              message.info('复制功能待实现')
              break
            case 'settings':
              // 菜单设置逻辑
              message.info('设置功能待实现')
              break
            case 'delete':
              handleDelete(record)
              break
          }
        }

        return (
          <Space size="small">
            <Button
              type="link"
              size="small"
              style={{ color: '#1890ff', padding: 0 }}
              onClick={() => handleEdit(record)}
            >
              编辑
            </Button>
            <Button
              type="link"
              size="small"
              style={{ color: record.hidden ? '#52c41a' : '#faad14', padding: 0 }}
              onClick={() => handleToggleVisibility(record)}
            >
              {record.hidden ? '显示' : '隐藏'}
            </Button>
            <Button
              type="link"
              size="small"
              danger
              style={{ padding: 0 }}
              onClick={() => handleDelete(record)}
            >
              删除
            </Button>
            <Dropdown
              menu={{
                items: moreMenuItems,
                onClick: handleMoreMenuClick,
              }}
              placement="bottomRight"
              trigger={['click']}
            >
              <Button
                type="text"
                size="small"
                icon={<MoreOutlined />}
                style={{ color: '#666' }}
              />
            </Dropdown>
          </Space>
        )
      }
    }
  ]

  // 处理添加菜单
  const handleAdd = (parentKey?: string) => {
    setModalType('create')
    setCurrentMenu(null)
    form.resetFields()
    if (parentKey) {
      form.setFieldsValue({ parentKey })
    }
    setModalVisible(true)
  }

  // 处理编辑菜单
  const handleEdit = (menu: MenuItem) => {
    setModalType('edit')
    setCurrentMenu(menu)
    form.setFieldsValue({
      name: menu.name,
      key: menu.key,
      parentKey: getParentId(menu.key)?.toString(),
      path: menu.path,
      icon: menu.icon,
      component: menu.component,
      hidden: menu.hidden || false,
      breadcrumbHidden: menu.breadcrumbHidden || false,
      permission: Array.isArray(menu.permission) 
        ? menu.permission.join(',') 
        : typeof menu.permission === 'string' 
          ? menu.permission 
          : '',
      keepAlive: menu.meta?.keepAlive || false,
      affix: menu.meta?.affix || false,
      closable: menu.meta?.closable !== false
    })
    setModalVisible(true)
  }

  // 获取父级菜单ID
  const getParentId = (targetKey: string): number | undefined => {
    const findParent = (nodes: MenuTableData[], key: string): number | undefined => {
      for (const node of nodes) {
        if (node.children) {
          for (const child of node.children) {
            if (child.key === key) {
              return node.id
            }
          }
          const parentId = findParent(node.children, key)
          if (parentId) return parentId
        }
      }
      return undefined
    }
    return findParent(menuData, targetKey)
  }

  // 处理删除菜单
  const handleDelete = async (record: MenuTableData) => {
    try {
      console.log('🚀 [删除菜单] 菜单数据:', record)
      console.log('🚀 [删除菜单] 菜单ID:', record.id)
      
      if (!record.id) {
        message.error('菜单ID无效')
        return
      }
      
      const response = await menuService.deleteMenu(record.id)
      if (response.code === 200) {
        message.success('删除成功')
        fetchMenus()
      } else {
        message.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除菜单失败:', error)
      message.error('删除失败')
    }
  }

  // 处理切换显示/隐藏
  const handleToggleVisibility = async (menu: MenuItem) => {
    try {
      const response = await menuService.toggleMenuVisibility(menu.key, !menu.hidden)
      if (response.code === 200) {
        message.success(`${menu.hidden ? '显示' : '隐藏'}成功`)
        fetchMenus()
      } else {
        message.error(response.message || '操作失败')
      }
    } catch (error) {
      console.error('切换菜单显示状态失败:', error)
      message.error('操作失败')
    }
  }

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      // 转换前端数据格式为后端期望的格式
      const formData = {
        name: values.name,
        key: values.key,
        parentId: values.parentKey ? parseInt(values.parentKey) : null,
        path: values.path,
        icon: values.icon,
        component: values.component,
        hidden: values.hidden || false,
        breadcrumbHidden: values.breadcrumbHidden || false,
        permission: values.permission ? values.permission.split(',').map((p: string) => p.trim()).join(',') : null,
        title: values.name,
        keepAlive: values.keepAlive || false,
        affix: values.affix || false,
        closable: values.closable !== false,
        type: 2, // 默认为菜单类型
        sort: 0,
        status: 1
      }

      console.log('🚀 [提交表单] 发送的数据:', formData)

      let response
      if (modalType === 'create') {
        response = await menuService.createMenu(formData)
      } else {
        response = await menuService.updateMenu(currentMenu!.key, formData)
      }

      if (response.code === 200) {
        message.success(modalType === 'create' ? '创建成功' : '更新成功')
        setModalVisible(false)
        form.resetFields()
        fetchMenus()
      } else {
        message.error(response.message || '操作失败')
      }
    } catch (error) {
      console.error('提交表单失败:', error)
      message.error('操作失败')
    }
  }

  // 树形选择器数据转换
  const transformToTreeSelectData = (nodes: MenuTableData[]): any[] => {
    return nodes.map(node => ({
      title: node.name,
      value: node.id,
      children: node.children ? transformToTreeSelectData(node.children) : undefined
    }))
  }

  // 组件挂载时获取数据
  useEffect(() => {
    fetchMenus()
  }, [])

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys)
    },
    getCheckboxProps: () => ({
      disabled: false, // 可以根据需要设置禁用条件
    }),
  }

  return (
    <div className={styles.menuPage}>

      {/* 操作工具栏 */}
      <Card 
        size="small" 
        className={styles.toolbarCard}
      >
        <div className={styles.toolbar}>
          <div className={styles.toolbarLeft}>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => handleAdd()}
              className={styles.actionButton}
            >
              新增菜单
            </Button>
            <Button
              danger
              icon={<DeleteOutlined />}
              onClick={handleBatchDelete}
              disabled={selectedRowKeys.length === 0}
              className={styles.actionButton}
            >
              批量删除
            </Button>
            <div className={styles.divider} />
            <Button
              icon={<ExpandOutlined />}
              onClick={expandAll}
              disabled={loading}
              size="small"
              className={styles.actionButton}
            >
              展开全部
            </Button>
            <Button
              icon={<CompressOutlined />}
              onClick={collapseAll}
              disabled={loading}
              size="small"
              className={styles.actionButton}
            >
              折叠全部
            </Button>
          </div>
          
          <div className={styles.toolbarRight}>
            {selectedRowKeys.length > 0 && (
              <span className={styles.selectedInfo}>
                已选择 <span className={styles.selectedCount}>{selectedRowKeys.length}</span> 项
              </span>
            )}
            <Button
              icon={<ReloadOutlined />}
              onClick={fetchMenus}
              loading={loading}
              className={styles.actionButton}
            >
              刷新
            </Button>
          </div>
        </div>
      </Card>

      {/* 表格区域 */}
      <Card className={styles.tableCard} bodyStyle={{ padding: 0 }}>
        <Table
          columns={columns}
          dataSource={menuData}
          loading={loading}
          pagination={false}
          rowSelection={rowSelection}
          expandable={{
            expandedRowKeys,
            onExpandedRowsChange: (keys) => setExpandedRowKeys([...keys]),
            indentSize: 24,
          }}
          onRow={(record) => ({
            className: 'menu-table-row',
            style: { cursor: 'pointer' },
            onClick: (e) => {
              // 避免点击复选框时触发
              if ((e.target as HTMLElement).closest('.ant-checkbox-wrapper')) {
                return
              }
              if (record.children && record.children.length > 0) {
                const isExpanded = expandedRowKeys.includes(record.key)
                if (!isExpanded) {
                  setExpandedRowKeys([...expandedRowKeys, record.key])
                }
              }
            },
            onDoubleClick: () => {
              setExpandedRowKeys(expandedRowKeys.filter(key => key !== record.key))
            }
          })}
          rowKey="key"
          scroll={{ x: 1200 }}
          size="middle"
          locale={{
            emptyText: (
              <div className={styles.emptyState}>
                <MenuOutlined className={styles.emptyIcon} />
                <div className={styles.emptyText}>暂无菜单数据</div>
                <div className={styles.emptyDescription}>
                  点击上方"新增菜单"按钮开始创建菜单
                </div>
              </div>
            )
          }}
          style={{
            borderRadius: 0,
          }}
        />
      </Card>

      {/* 添加/编辑菜单弹窗 */}
      <Modal
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {modalType === 'create' ? <PlusOutlined /> : <EditOutlined />}
            <span>{modalType === 'create' ? '添加菜单' : '编辑菜单'}</span>
          </div>
        }
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false)
          form.resetFields()
        }}
        onOk={() => form.submit()}
        width={900}
        destroyOnClose
        style={{ top: 20 }}
        className="menu-modal"
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            hidden: false,
            breadcrumbHidden: false,
            keepAlive: false,
            affix: false,
            closable: true
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="菜单名称"
                name="name"
                rules={[{ required: true, message: '请输入菜单名称' }]}
              >
                <Input placeholder="请输入菜单名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="菜单标识"
                name="key"
                rules={[
                  { required: true, message: '请输入菜单标识' },
                  { pattern: /^[a-zA-Z0-9_-]+$/, message: '只能包含字母、数字、下划线和横线' }
                ]}
              >
                <Input placeholder="请输入菜单标识" disabled={modalType === 'edit'} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="父级菜单" name="parentKey">
                <TreeSelect
                  placeholder="请选择父级菜单（不选则为根菜单）"
                  allowClear
                  treeData={transformToTreeSelectData(parentOptions)}
                  treeDefaultExpandAll
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="路由路径" name="path">
                <Input placeholder="请输入路由路径，如：/system/menu" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="图标" name="icon">
                <Input placeholder="请输入图标名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="组件路径" name="component">
                <Input placeholder="请输入组件路径，如：System/Menu" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item label="权限标识" name="permission">
            <Input.TextArea
              placeholder="请输入权限标识，多个用英文逗号分隔"
              rows={2}
            />
          </Form.Item>

          <Divider orientation="left" style={{ margin: '24px 0 16px 0' }}>
            <span style={{ color: '#666', fontSize: '14px', fontWeight: 500 }}>显示设置</span>
          </Divider>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item label="隐藏菜单" name="hidden" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="隐藏面包屑" name="breadcrumbHidden" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="页面缓存" name="keepAlive" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item label="固定标签页" name="affix" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="可关闭标签页" name="closable" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  )
}

export default Menus